#!/usr/bin/env node

import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import readline from 'readline';
import { execSync } from 'child_process';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const packagePath = path.join(__dirname, '../package.json');
const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf8'));

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

// 解析版本号并增加最后一位
function incrementVersion(version) {
  const parts = version.split('.');
  parts[2] = parseInt(parts[2]) + 1;
  return parts.join('.');
}

// 验证版本号格式
function isValidVersion(version) {
  return /^\d+\.\d+\.\d+$/.test(version);
}

async function publish() {
  const currentVersion = packageJson.version;
  console.log(`Current version: ${currentVersion}`);
  
  try {
    // 检查是否有未提交的更改
    try {
      execSync('git diff --quiet && git diff --staged --quiet');
    } catch (e) {
      console.error('\x1b[31m%s\x1b[0m', '错误: 有未提交的更改，请先提交或存储您的更改。');
      process.exit(1);
    }

    // 获取新版本号
    const newVersion = await new Promise((resolve) => {
      rl.question(`Enter new version (press Enter for ${incrementVersion(currentVersion)}): `, (input) => {
        const version = input.trim() || incrementVersion(currentVersion);
        if (!isValidVersion(version)) {
          console.error('\x1b[31m%s\x1b[0m', '错误: 版本号格式无效，请使用 x.x.x 格式');
          rl.close();
          process.exit(1);
        }
        resolve(version);
      });
    });

    // 更新 package.json
    packageJson.version = newVersion;
    fs.writeFileSync(packagePath, JSON.stringify(packageJson, null, 2) + '\n');
    
    console.log('\x1b[36m%s\x1b[0m', `\n正在发布版本 ${newVersion}...`);

    // 执行生产构建
    console.log('\x1b[36m%s\x1b[0m', '\n1. 执行生产构建...');
    execSync('npm run build:prod', { stdio: 'inherit' });

    // 提交版本更新
    console.log('\x1b[36m%s\x1b[0m', '\n2. 提交版本更新...');
    execSync('git add package.json');
    execSync(`git commit -m "chore: release v${newVersion}"`);
    
    // 创建标签
    console.log('\x1b[36m%s\x1b[0m', '\n3. 创建 Git 标签...');
    execSync(`git tag v${newVersion}`);
    
    // 推送到远程仓库
    console.log('\x1b[36m%s\x1b[0m', '\n4. 推送到远程仓库...');
    execSync('git push');
    execSync('git push --tags');
    
    // 发布到 npm
    console.log('\x1b[36m%s\x1b[0m', '\n5. 发布到 npm...');
    execSync('npm publish', { stdio: 'inherit' });
    
    console.log('\x1b[32m%s\x1b[0m', `\n✨ 成功发布版本 ${newVersion}！`);
  } catch (error) {
    console.error('\x1b[31m%s\x1b[0m', '\n发布失败：', error.message);
    // 发生错误时回滚版本号
    fs.writeFileSync(packagePath, JSON.stringify({ ...packageJson, version: currentVersion }, null, 2) + '\n');
    process.exit(1);
  } finally {
    rl.close();
  }
}

publish();
